<template>
  <div class="addBrand-container" id="member-add-app">
    <div class="container">
      <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="180px"
          class="demo-ruleForm"
      >
        <el-form-item label="账号:" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入账号" maxlength="20" />
        </el-form-item>

        <el-form-item label="员工姓名:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入员工姓名" maxlength="20" />
        </el-form-item>

        <el-form-item label="手机号:" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入手机号" maxlength="20" />
        </el-form-item>

        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="身份证号:" prop="idNumber">
          <el-input v-model="ruleForm.idNumber" placeholder="请输入身份证号" maxlength="20" />
        </el-form-item>

        <el-form-item>
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm(false)">保存</el-button>
          <el-button v-if="actionType === 'add'" type="primary" class="continue" @click="submitForm(true)">
            保存并继续添加
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  addEmployee,
  editEmployee,
  queryEmployeeById
} from '@/api/member'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 数据定义
const id = ref('')
const actionType = ref('add')
const ruleForm = ref({
  username: '',
  name: '',
  phone: '',
  sex: '男',
  idNumber: ''
})

const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error('账号不能为空'))
  } else if (value.length > 20) {
    callback(new Error('账号不能超过20个字符'))
  } else {
    callback()
  }
}

const validateName = (rule, value, callback) => {
  if (!value) {
    callback(new Error('员工姓名不能为空'))
  } else if (value.length > 20) {
    callback(new Error('姓名不能超过20个字符'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  const reg = /^1[3|5|7|8][0-9]{10}$/
  if (!value) {
    callback(new Error('手机号不能为空'))
  } else if (!reg.test(value)) {
    callback(new Error('手机号格式错误'))
  } else {
    callback()
  }
}

const validateIdNumber = (rule, value, callback) => {
  const reg = /(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x)$)/
  if (!value) {
    callback(new Error('身份证号不能为空'))
  } else if (!reg.test(value)) {
    callback(new Error('身份证号格式错误'))
  } else {
    callback()
  }
}

const rules = {
  username: [{ validator: validateUsername, trigger: 'blur' }],
  name: [{ validator: validateName, trigger: 'blur' }],
  phone: [{ validator: validatePhone, trigger: 'blur' }],
  idNumber: [{ validator: validateIdNumber, trigger: 'blur' }]
}

// 获取 URL 参数
const init = async () => {
  const params = new URLSearchParams(window.location.search)
  id.value = params.get('id')
  actionType.value = id.value ? 'edit' : 'add'

  if (id.value) {
    try {
      const res = await queryEmployeeById(id.value)
      if (res.code === 1) {
        ruleForm.value = res.data
        ruleForm.value.sex = res.data.sex === '0' ? '女' : '男'
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (err) {
      ElMessage.error('请求出错了：' + err)
    }
  }
}

// 提交表单
const submitForm = async (st) => {
  const valid = await validateForm()
  if (valid) {
    const params = {
      ...ruleForm.value,
      sex: ruleForm.value.sex === '女' ? '0' : '1'
    }

    try {
      let res
      if (actionType.value === 'add') {
        res = await addEmployee(params)
        if (res.code === 1) {
          ElMessage.success('员工添加成功！')
          if (!st) {
            goBack()
          } else {
            ruleForm.value = {
              username: '',
              name: '',
              phone: '',
              sex: '男',
              idNumber: ''
            }
          }
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } else {
        res = await editEmployee({ ...params, id: id.value })
        if (res.code === 1) {
          ElMessage.success('员工信息修改成功！')
          goBack()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      }
    } catch (err) {
      ElMessage.error('请求出错了：' + err)
    }
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 表单验证
const formRef = ref(null)

const validateForm = async () => {
  return new Promise((resolve) => {
    formRef.value.validate(valid => {
      resolve(valid)
    })
  })
}

onMounted(() => {
  init()
})
</script>

<style scoped>
.addBrand-container .notAdmin::after {
  border: 0 !important;
}
.continue {
  margin-left: 10px;
}
</style>
